package com.rpay.web.controller.user;

import com.rpay.common.dto.sms.SmsCodeDTO;
import com.rpay.common.dto.user.UserDTO;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.enums.SmsCodeEnum;
import com.rpay.common.exception.UserException;
import com.rpay.common.util.LoggerUtil;
import com.rpay.common.util.Md5Util;
import com.rpay.common.util.StringUtil;
import com.rpay.common.vo.PcsResult;
import com.rpay.service.user.IUserService;
import com.rpay.web.controller.BaseController;
import com.rpay.web.interceptor.authentic.AccessControl;
import com.rpay.web.interceptor.authentic.AccessControlType;
import com.rpay.web.param.LoginUser;
import com.rpay.web.param.RegisterUser;
import com.rpay.web.param.ResetPwd;
import com.rpay.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * Title：
 * Description
 *
 * @author fxg06 on 2018/4/20
 * @version 1.0
 */
@RestController
@RequestMapping(value = "api/user")
@AccessControl(type = AccessControlType.SECRET)
@Validated
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private IUserService iUserService;

    @PostMapping(value = "login")
    public PcsResult login(@RequestBody @Validated LoginUser loginUser) {
        UserDTO userDTO = userService.login(loginUser);
        return PcsResult.build(userDTO);
    }

    @PostMapping(value = "register")
    public PcsResult register(@RequestBody @Validated RegisterUser registerUser) {
        userService.register(registerUser);
        return newResult();
    }

    @PutMapping(value = "resetPwd")
    public PcsResult resetPwd(@Validated @RequestBody ResetPwd resetPwd) {
        UserDTO userDTO = iUserService.getUserByAccount(resetPwd.getReceiver());
        if (userDTO == null) {
            throw new UserException(PcsResultCode.USER_NOT_EXISTED);
        }
        SmsCodeDTO smsCodeDTO = new SmsCodeDTO();
        smsCodeDTO.setReceiver(resetPwd.getReceiver());
        smsCodeDTO.setType(resetPwd.getType());
        smsCodeDTO.setVerifyType(SmsCodeEnum.FORGET_PWD.getCode());
        smsCodeDTO.setCode(resetPwd.getCode());

        userDTO.setPassword(Md5Util.encrypt(resetPwd.getPassword()));
        userService.modifyPwd(userDTO, smsCodeDTO);
        return newResult();
    }



}
